﻿using System;
using weka.classifiers;
using weka.core;
using weka.filters.unsupervised.attribute;
using weka.filters;
using weka.filters.unsupervised.instance;
using System.Diagnostics;

namespace OMC.Classification
{
    class Evaluator
    {
        private Instances rawData = null;
        private Instances train = null;
        private Instances test = null;
        private Classifier classifier = null;
        const int percentSplit = 66;
        private StringToWordVector filter = new StringToWordVector();
        private RemovePercentage percentageSplitter = new RemovePercentage();
        private static string goodnessExtraInfos = "";
        private double evalSolution = 0.0;

        public Evaluator(Instances rawData, Classifier classifier)
        {
            try
            {
                filter.setInputFormat(rawData);
                this.rawData = Filter.useFilter(rawData, filter);
                this.classifier = classifier;
            }
            catch (Exception ex)
            {
                String message = "It isn't possible to init an Evaluator";
                Utils.Debug.Log(message, ex, TraceEventType.Error);
            }
        }


        public int getGoodness()
        {
            try
            {
                //randomize the order of the instances in the dataset.
                Filter myRandom = new weka.filters.unsupervised.instance.Randomize();
                myRandom.setInputFormat(rawData);
                rawData = Filter.useFilter(rawData, myRandom);

                int trainSize = rawData.numInstances() * percentSplit / 100;
                int testSize = rawData.numInstances() - trainSize;
                train = new Instances(rawData, 0, trainSize);
                test = new Instances(rawData, trainSize, testSize);

                // train classifier
                classifier.buildClassifier(train);
                // evaluate classifier
                Evaluation eval = new Evaluation(train);
                eval.evaluateModel(classifier, test);
                goodnessExtraInfos = eval.toSummaryString("\nResults\n======\n", false)
                                     + "\n======\n *new random every App start!";
                evalSolution = eval.pctCorrect();
            }
            catch (Exception ex)
            {
                String message = "It isn't possible to get Goodness";
                Utils.Debug.Log(message, ex, TraceEventType.Error);
            }
            return (int)evalSolution;
        }

        public static string GetGoodnessExtra()
        {
            return goodnessExtraInfos;
        }
    }
}